package ntd.util.frame.msg.service.handle.jpush.sms;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.StaticLog;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import cn.jsms.api.template.SendTempSMSResult;
import cn.jsms.api.template.TempSMSResult;
import cn.jsms.api.template.TemplatePayload;
import lombok.Data;

import ntd.util.frame.msg.bo.MsgConfig;
import ntd.util.UtilCatch;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JPushSmsHelper {

    private SMSClient smsClient;

    public JPushSmsHelper(MsgConfig msgConfig) {
        smsClient = new SMSClient(msgConfig.getSecret(), msgConfig.getAppKey());
    }

    public void sendSms(JPushSmsInBO jPushSmsInBO) {
        List<String> phones = jPushSmsInBO.getPhones();
        if (CollectionUtil.isEmpty(phones)) {
            return;
        }
        SMSPayload.Builder builder = buildSmsPayload(jPushSmsInBO);
        for (String phone : phones) {
            SMSPayload build = builder.setMobileNumber(phone).build();
            SendSMSResult res = UtilCatch.tryCatch(() -> smsClient.sendTemplateSMS(build));
            if (ObjectUtil.isNotNull(res) && !res.isResultOK()) {
                StaticLog.error(res.getOriginalContent());
            }
        }
    }

    public TempSMSResult getSmsTemplate(String id) {
        TempSMSResult tempSMSResult = UtilCatch.tryCatch(() -> smsClient.checkTemplate(Integer.parseInt(id)));
        return tempSMSResult;
    }

    public SendTempSMSResult saveSmsTemplate(TemplatePayload templatePayload) {
        return UtilCatch.tryCatch(() -> smsClient.createTemplate(templatePayload));
    }

    private SMSPayload.Builder buildSmsPayload(JPushSmsInBO jPushSmsInBO) {
        SMSPayload.Builder builder = SMSPayload.newBuilder().setTempId(jPushSmsInBO.getSmsTempId());
        for (Map.Entry<String, String> param : jPushSmsInBO.getParams().entrySet()) {
            builder.addTempPara(param.getKey(), param.getValue());
        }
        int signId = jPushSmsInBO.getSignId();
        if (signId > 0) {
            builder.setSignId(signId);
        }
        return builder;
    }

    @Data
    public static class JPushSmsInBO {

        private List<String> phones;
        private int smsTempId;
        private int signId = -1;
        private Map<String, String> params = new HashMap<>();

    }
}